using System.Text.Json;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace Beauty.Net.RabbitMQ
{
    /// <summary>
    /// 消息处理委托
    /// </summary>
    public delegate void MessageHandler<T>(T message, Dictionary<string, object>? headers = null);

    /// <summary>
    /// RabbitMQ消费者接口
    /// </summary>
    public interface IRabbitMQConsumer
    {
        /// <summary>
        /// 启动消费
        /// </summary>
        void Start();

        /// <summary>
        /// 停止消费
        /// </summary>
        void Stop();
    }

    /// <summary>
    /// RabbitMQ消费者基类
    /// </summary>
    public abstract class RabbitMQConsumerBase<T> : IRabbitMQConsumer, IDisposable
    {
        protected readonly IRabbitMQConnectionManager _connectionManager;
        protected readonly JsonSerializerOptions _jsonOptions;
        protected IModel? _channel;
        protected EventingBasicConsumer? _consumer;
        protected bool _isRunning = false;

        protected string ExchangeName { get; set; }
        protected string QueueName { get; set; }
        protected string RoutingKey { get; set; }
        protected bool AutoAck { get; set; }
        protected MessageHandler<T> MessageHandler { get; set; }

        protected RabbitMQConsumerBase(IRabbitMQConnectionManager connectionManager,
                                      string exchangeName,
                                      string queueName,
                                      string routingKey,
                                      MessageHandler<T> messageHandler,
                                      bool autoAck = false)
        {
            _connectionManager = connectionManager;
            ExchangeName = exchangeName;
            QueueName = queueName;
            RoutingKey = routingKey;
            MessageHandler = messageHandler;
            AutoAck = autoAck;

            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
        }

        /// <summary>
        /// 设置交换机和队列（由子类实现）
        /// </summary>
        protected abstract void SetupExchangeAndQueue();

        /// <summary>
        /// 处理消息
        /// </summary>
        protected virtual void HandleMessage(BasicDeliverEventArgs ea)
        {
            try
            {
                var body = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                var obj = JsonSerializer.Deserialize<T>(message, _jsonOptions);

                if (obj != null)
                {
                    var headers = ea.BasicProperties.Headers?.ToDictionary(k => k.Key, v => v.Value);
                    MessageHandler(obj, headers);
                }

                if (!AutoAck && _channel != null)
                {
                    _channel.BasicAck(ea.DeliveryTag, false);
                }
            }
            catch (Exception ex)
            {
                if (!AutoAck && _channel != null)
                {
                    // 可以根据需要选择拒绝或重新入队
                    _channel.BasicNack(ea.DeliveryTag, false, requeue: false);
                }
                // 这里可以添加日志记录
            }
        }

        public virtual void Start()
        {
            if (_isRunning)
                return;

            _channel = _connectionManager.CreateChannel();
            SetupExchangeAndQueue();

            _consumer = new EventingBasicConsumer(_channel);
            _consumer.Received += (model, ea) => HandleMessage(ea);

            _channel.BasicConsume(queue: QueueName, autoAck: AutoAck, consumer: _consumer);
            _isRunning = true;
        }

        public virtual void Stop()
        {
            if (!_isRunning)
                return;

            _isRunning = false;
            
            if (_channel != null)
            {
                _channel.Close();
                _channel.Dispose();
                _channel = null;
            }
        }

        public void Dispose()
        {
            Stop();
        }
    }
}